package com.wxq.yaoxia.disease;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.wxq.net.NetClient;
import com.wxq.net.NetWorkThread;
import com.wxq.net.NetWorkUserInterface;
import com.wxq.yaoxia.R;
import com.wxq.yaoxia.drug.YXDrugDetailActivity;
import com.wxq.yaoxia.mainborad.YXMainboradActivity;
import com.wxq.yaoxia.util.YXConstants;
import com.wxq.yaoxia.util.YXUtility;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


public class YXDiseaseDetail extends TabActivity implements NetWorkUserInterface{

	private TabHost myTabhost;
	ListView symptomLV;
	ListView drugLV;
	WebView introductionTV;
	
	String queryId;
	
	String briefUrl;
	JSONArray symptomArray;
	JSONArray drugArray;
	JSONArray commonArray;
	JSONArray brandArray;
	
	Handler mHandler = new Handler();
	ProgressDialog progressDialog;
	
	boolean showCommon = true;
	
	RadioGroup changeDrugRG;
	RadioButton commonBtn;
	RadioButton brandBtn;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        setContentViewWithTopbar(R.layout.yx_disease_tabhost,R.layout.yx_topbar);
        
        myTabhost=this.getTabHost();       
        LayoutInflater.from(this).inflate(R.layout.yx_disease_tab, myTabhost.getTabContentView(), true);
        //myTabhost.setBackgroundColor(Color.argb(150, 22, 70, 150));
        
        myTabhost.addTab(myTabhost.newTabSpec("One")
        				.setIndicator("简介", getResources().getDrawable(R.drawable.disease_detail_pref))
                        .setContent(R.id.linearLayout_red));
        myTabhost.addTab(myTabhost.newTabSpec("Two")
                		.setIndicator("症状",getResources().getDrawable(R.drawable.disease_detail_sym))
                        .setContent(R.id.linearLayout_blue));
        myTabhost.addTab(myTabhost.newTabSpec("Three")
                		.setIndicator("治疗药物",getResources().getDrawable(R.drawable.disease_detail_drug))
                        .setContent(R.id.linearLayout_green));   
        
        introductionTV = (WebView) findViewById(R.id.introductionTV);
        symptomLV = (ListView) findViewById(R.id.symptomLV);
        drugLV = (ListView) findViewById(R.id.drugLV);
        changeDrugRG = (RadioGroup) findViewById(R.id.rBtnGrp);
        commonBtn = (RadioButton) findViewById(R.id.commonBtn);
        brandBtn = (RadioButton) findViewById(R.id.brandBtn);
        showCommon = commonBtn.isChecked();
        
        changeDrugRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				showCommon = commonBtn.isChecked();
				setDrugListView();
			}
		});
        
        queryId = getIntent().getStringExtra(YXConstants.COLUMN_QueryId);
        
        drugLV.setOnItemClickListener(
				new OnItemClickListener()
				{

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
//						Intent intent = new Intent();		
//						intent.setAction(Intent.ACTION_SEARCH);
//						intent.putExtra(SearchManager.QUERY, drugArray.optJSONObject(position).optString("name"));
//						intent.setClass(YXDiseaseDetail.this, YXDrugSearchResultActivity.class);						
//						YXDiseaseDetail.this.startActivity(intent);
						JSONArray tempArray;
						if (showCommon) {
							tempArray = commonArray;
						}
						else {
							tempArray = brandArray;
						}
						Intent newIntent = new Intent();
						newIntent.putExtra(YXConstants.KEY_ID, 1);
						newIntent.putExtra(YXConstants.COLUMN_Name, tempArray.optJSONObject(position).optString("name"));
						newIntent.putExtra(YXConstants.DRUG_COLUMN_BrandName, tempArray.optJSONObject(position).optString("brandname"));
						newIntent.putExtra(YXConstants.DRUG_COLUMN_CommonName, tempArray.optJSONObject(position).optString("commonname"));
						newIntent.putExtra(YXConstants.COLUMN_QueryId, tempArray.optJSONObject(position).optString("queryid"));
						newIntent.setClass(YXDiseaseDetail.this, YXDrugDetailActivity.class);
						YXDiseaseDetail.this.startActivity(newIntent);
					}
					
				});
        
        //获得网络数据
      	NetWorkThread netWorkThread = new NetWorkThread(this, this, mHandler);
      	netWorkThread.start();
    }
    
    @SuppressLint("DefaultLocale")
	public void getDetailInfo() {
    	String flag = "B90";
		String key = queryId;
		String timestamp = Calendar.getInstance().getTime().getTime()+""; 
		String checksum = YXUtility.encryptToMD5(timestamp+flag+timestamp+key+timestamp+"yaoxia");
		String url = String.format(YXConstants.URL_DETAIL, flag,key,timestamp,checksum.toLowerCase());
		//Log.d("wxq", "url = "+url);
		String result = NetClient.doGet(url);
		//Log.d("wxq", "result = "+result);
		if(TextUtils.isEmpty(result))
		{
			YXUtility.showToast(this, "Get data erro,please check your network!", mHandler);
		}
		try {
			JSONObject resultJSON = new JSONObject(result);
			int code = resultJSON.getInt("code");
			String msg = resultJSON.getString("message");
			if(code == 500)
			{
				YXUtility.showToast(this, msg, mHandler);
			}
			else if(code == 200)
			{
				//
				briefUrl = resultJSON.getString("briefUrl");
				symptomArray = resultJSON.getJSONArray("symptomArray");
				drugArray = resultJSON.getJSONArray("drugArray");
				commonArray = new JSONArray();
				brandArray =  new JSONArray();
				for (int i = 0; i < drugArray.length(); i++) {
					if ("0".equals(drugArray.optJSONObject(i).optString("flag"))) {
						commonArray.put(drugArray.optJSONObject(i));
					}
					else {
						brandArray.put(drugArray.optJSONObject(i));
					}
				}
				Log.d("wxq", "commonSize="+commonArray.length()+",brandSize="+brandArray.length());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void setTopBarButtonListener() {
		// 
		Button leftBtn = (Button) findViewById(R.id.btnLeft);
    	Button rightBtnButton = (Button) findViewById(R.id.btnRight);
    	TextView centerTV = (TextView) findViewById(R.id.centerTV);
    	
    	leftBtn.setVisibility(View.VISIBLE);
    	leftBtn.setText("返回");
    	leftBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
    	rightBtnButton.setVisibility(View.VISIBLE);
//    	rightBtnButton.setText("药");
    	rightBtnButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(YXDiseaseDetail.this, YXMainboradActivity.class);
				YXDiseaseDetail.this.startActivity(intent);
			}
		});
    	centerTV.setVisibility(View.VISIBLE);
    	
    	centerTV.setText(getIntent().getStringExtra(YXConstants.COLUMN_Name));
	}
    
    public void setContentViewWithTopbar(int mainRes,int topbarRes) {
		LayoutInflater inflater = LayoutInflater.from(this);
    	LinearLayout mainLayout = (LinearLayout) inflater.inflate(mainRes, null);
        LinearLayout topBarLayout = (LinearLayout) mainLayout.findViewById(R.id.topBarLayout);
        
        View topBar = inflater.inflate(topbarRes, null);
    	
    	topBarLayout.addView(topBar);
    	
		this.setContentView(mainLayout);
		setTopBarButtonListener();
	}
    
    public View getIndicatorView(String title,Drawable drawable) {
    	LayoutInflater inflater = LayoutInflater.from(this);
    	View v = inflater.inflate(R.layout.yx_disease_tab_indicator, null);
    	TextView tv = (TextView) v.findViewById(R.id.title);
    	tv.setText(title);
    	
    	if(drawable!=null)
    	{
    		ImageView iv = (ImageView) v.findViewById(R.id.icon);
    		iv.setImageDrawable(drawable);
    	}
    	return v;
	}
    
    public List<Map<String, String>> getSymptomData() {
		List<Map<String, String>> list = new ArrayList<Map<String,String>>();
		if(symptomArray!=null)
		{
			for(int i = 0;i<symptomArray.length();i++)
			{
				try {
					Map<String, String>tempMap = new HashMap<String, String>();
					tempMap.put("name", symptomArray.getJSONObject(i).getString("name"));
					list.add(tempMap);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return list;
	}
	
	public void setSymptomListView() {
		List<Map<String, String>> list = getSymptomData();
		//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.shool_item, list);
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.shool_item, new String[]{"name"}, new int []{android.R.id.text1});
		symptomLV.setAdapter(simpleAdapter);
	}
	
	public List<Map<String, String>> getDrugData() {
		List<Map<String, String>> list = new ArrayList<Map<String,String>>();
		if(drugArray!=null)
		{
			if (showCommon) {
				//通用名
				for(int i = 0;i<commonArray.length();i++)
				{
					Map<String, String> tempMap = new HashMap<String, String>();
					try {
						tempMap.put("name",commonArray.getJSONObject(i).getString("name"));
						tempMap.put("commonname", commonArray.getJSONObject(i).getString("commonname"));
						list.add(tempMap);
					
					} catch (JSONException e) {
						//
						e.printStackTrace();
					}
				}
			}
			else {
				//商品名
				for(int i = 0;i<brandArray.length();i++)
				{
					Map<String, String> tempMap = new HashMap<String, String>();
					try {
						tempMap.put("name",brandArray.getJSONObject(i).getString("name"));
						tempMap.put("commonname", brandArray.getJSONObject(i).getString("commonname"));
						list.add(tempMap);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return list;
	}
	
	public void setDrugListView() {
		List<Map<String, String>> list = getDrugData();
		//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.shool_item, list);
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.disease_list_item, new String[]{"name","commonname"}, new int []{android.R.id.text1,R.id.subTitle});
		drugLV.setAdapter(simpleAdapter);
	}
	
	@SuppressLint("SetJavaScriptEnabled") 
	public void setIntroduction() {
		if(TextUtils.isEmpty(briefUrl))
		{
			return;
		}
		WebSettings webSettings = introductionTV.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setSupportZoom(true);
		introductionTV.loadUrl(briefUrl);
	}

	@Override
	public void beforeNetwork() {
		//添加提示信息
		progressDialog = new ProgressDialog(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setTitle("正在处理中...");
		progressDialog.setMessage("正在请求数据...");
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	@Override
	public void getNetworkData() {
		getDetailInfo();
	}

	@Override
	public void afterNetwork() {
		//移除提示信息
		progressDialog.cancel();
		setIntroduction();
        setSymptomListView();
        setDrugListView();
	}

}
